package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.ContainerDTO;
import com.arpa.wms.domain.dto.ContainerExcelDTO;
import com.arpa.wms.domain.entity.Container;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.ContainerVO;
import com.arpa.wms.service.IContainerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 容器 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "容器")
@RestController
@RequestMapping(value="/container", produces = "application/json;charset=UTF-8")
@Log4j2
public class ContainerController {

   @Autowired
   private IContainerService  iContainerService;

    /**
     * 获取 容器 列表
     *
     * @param containerDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 容器 列表", notes = "获取 容器 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ContainerVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(ContainerDTO containerDTO,HttpServletRequest request) {
        try {
            containerDTO.setGroupCode(UserUtil.getBranchCode());
            ContainerVO containerVoSum = iContainerService.queryListSum(containerDTO);
            List<ContainerVO> containerVOList = iContainerService.queryList(containerDTO);

            Page returnPage = new Page(containerDTO.getPageNum(),containerDTO.getPageSize());
            returnPage.setRecords(containerVOList);
            returnPage.setTotal(containerVoSum.getTotal());
            returnPage.setSumObject(containerVoSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 容器
     *
     * @param entity Container
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 容器 ", notes = "添加 容器 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(Container.Save.class) Container entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            iContainerService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取容器详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取容器详情", notes = "获取容器详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "容器code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Container.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result container(@PathVariable String code, HttpServletRequest request) {
        try {
            Container entity = iContainerService.getOne(new QueryWrapper<Container>().lambda().eq(Container::getCode,code).eq(Container::getGroupCode,UserUtil.getBranchCode()));
            entity.setGroupCode(UserUtil.getBranchCode());
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改容器
     *
     * @param entity 容器
     * @param request
     * @return
     */
    @ApiOperation(value = "修改容器", notes = "修改容器")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(Container.Update.class) Container entity,HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iContainerService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 容器
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 容器 ", notes = "删除 容器 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            Map<String, Object> result = iContainerService.batchdel(codes);
            Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder buffer = new StringBuilder();
            buffer.append("删除成功").append(success).append("条；失败").append(failNum).append("条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    buffer.append("<br><font color='red'>容器【").append(m).append("】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(buffer.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
    /**
     * 启用
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "启用", notes = "启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iContainerService.activeStatus(codes, StatusEnum.ACTIVE);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 停用
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "停用", notes = "停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {

        Map<String, Object> result = iContainerService.activeStatus(codes, StatusEnum.UNACTIVE);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        List<String> barcodes = MapUtil.get(result, "barcodes", List.class);
        int failNum = codes.size() - success;
        StringBuilder buffer = new StringBuilder();
        buffer.append("停用成功").append(success).append("条；失败").append(failNum).append("条；");
        if(IterUtil.isNotEmpty(barcodes)){
            for (String m:barcodes) {
                buffer.append("<br><font color='red'>容器【").append(m).append("】停用失败，正在使用中;</font>");
            }
        }
        return Result.ok(buffer.toString());
    }

    /**
     * 获取可用的容器信息
     * @param receiveCode
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 可用容器 列表", notes = "获取 可用容器 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "receiveCode", value = "收货单编码", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ContainerVO.class))
    @NeedLogin
    @GetMapping("/canUseList")
    public Result canUseList(@RequestParam(value = "receiveCode", defaultValue = "") String receiveCode, HttpServletRequest request) {
        try {
            //获取可用容器列表(状态可用且未被占用）， 如果有收货单号，则范围可以增加该收货单中已占用的容器
            List<Container> containerList = iContainerService.queryCanUseList(receiveCode);
            return Result.ok().data(containerList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 容器导入预览
     * @param filePath
     * @param isView
     * @param request
     * @return
     */
    @ApiOperation(value = "容器 导入 预览", notes = "容器 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importPreviewList")
    public Result importPreviewList(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<ContainerExcelDTO> list = EasyExcelUtil.read(url.openStream(), ContainerExcelDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<ContainerVO> previewList = iContainerService.importPreviewList(list);
            return new Result().data(previewList);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 预览后导入库位
     * @param importCode 预览时生成的导入码
     * @param request
     * @return
     */
    @ApiOperation(value = "容器 导入", notes = "容器 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importContainer")
    public Result importContainer(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iContainerService.importContainer(importCode);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
